package com.maiji.cloud.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.maiji.cloud.entities.shopingmall.CapitalIOEntity;
import com.maiji.cloud.entities.shopingmall.CapitalMainLog;
import com.maiji.cloud.entities.shopingmall.WithdrawApply;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.shopingmall.*;
import com.maiji.cloud.request.shopingmall.PayResDto;
import com.maiji.cloud.response.*;
import com.maiji.cloud.response.shopingmall.*;
import com.maiji.cloud.service.CapitalIOService;
import com.maiji.cloud.service.CapitalMainService;
import com.maiji.cloud.service.WithdrawApplyService;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.service.CapitalMainLogService;

@RestController
@RequestMapping("/capital/")
public class CapitalController {

	Logger logger = LoggerFactory.getLogger(CouponsController.class);
    @Value("${lowestMoney}")
    private double lowestMoney;
	@Autowired
	private CapitalMainLogService capitalMainLogService;
	@Autowired
	private CapitalMainService capitalMainService;
	@Autowired
	private CapitalIOService capitalIOService;
    @Autowired
    private WithdrawApplyService withdrawApplyService;

	/**
	 * 获取用户的资金信息
	 * 
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("getCapitalInfo")
	public BaseDataResDto<CapitalInfoResData> getCapitalInfo(@RequestHeader(name = "maijiToken") String maijiToken) {
		logger.info("CapitalController.getCapitalInfo ,maijiToken is {}", maijiToken);
		return capitalMainService.getCapitalInfo(maijiToken);
	}

	/**
	 * 现金流水
	 * 
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("financialDetails")
	public FinancialDetailsResDto financialDetails(@RequestBody ReqMetaData param, @RequestHeader("maijiToken") String maijiToken) {
		logger.info("CapitalController.financialDetails,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.financialDetails(param, maijiToken);

	}

	/**
	 * 获得积分流水
	 * 
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("integralFlow")
	public IntegralFlowResDto integralFlow(@RequestBody ReqMetaData param, @RequestHeader("maijiToken") String maijiToken) {
		logger.info("CapitalController.integralFlow,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.integralFlow(param, maijiToken);
	}

	/**
	 * 积分消费流水
	 * @return
	 */
	@PostMapping("integralConsumeFlow")
	public IntegralFlowResDto integralConsumeFlow(@RequestBody ReqMetaData param, @RequestHeader("maijiToken") String maijiToken){
		logger.info("CapitalController.integralConsumeFlow,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.integralConsumeFlow(param, maijiToken);
	}

	/**
	 * 积分获得流水
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("integralAddFlow")
	public IntegralFlowResDto integralGainFlow(@RequestBody BaseDataReqDto<IntegralGainFlowReqData> param, @RequestHeader("maijiToken") String maijiToken) throws Exception{
		logger.info("CapitalController.integralGainFlow,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.integralGainFlow(param, maijiToken);
	}

	/**
	 * 减肥基金使用明细
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("reduceWeightFundConsumeFlow")
	public BaseDataResDto<List<FinancialDetailsResData>> reduceWeightFundConsumeFlow(@RequestBody ReqMetaData param, @RequestHeader("maijiToken") String maijiToken){
		logger.info("CapitalController.reduceWeightFundConsumeFlow,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		
		return capitalMainLogService.reduceWeightFundConsumeFlow(param, maijiToken);
	}
	
	/**
	 * 获得提现记录列表
	 * 
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("getcapitalIOList")
	public CapitalIOListResDto getcapitalIOList(@RequestBody BaseDataReqDto<CapitalIOListReqData> param, @RequestHeader("maijiToken") String maijiToken) {
		logger.info("CapitalController.getcapitalIOList,param is {},maijiToken is {}", JSON.toJSONString(param), maijiToken);
		return capitalMainLogService.getcapitalIOList(param, maijiToken);
	}
	
	/**
	 * 订单返现收入明细
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("getOrderReturnMoneyFlow")
	public BaseDataResDto<List<OrderReturnMoneyFlowResData>> getOrderReturnMoneyFlow(@RequestBody BaseDataReqDto<OrderReturnMoneyFlowReqData> param, @RequestHeader("maijiToken") String maijiToken){
		logger.info("CapitalController.getOrderReturnMoneyFlow,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.getOrderReturnMoneyFlow(param, maijiToken);
	} 

	/**
	 * 微信预支付
	 * 
	 * @return
	 * @throws Exception
	 */
	@PostMapping("weixinPay")
	public BaseDataResDto<Map<String, Object>> weixinPay(@RequestBody WeixinPayReqDto param, @RequestHeader("maijiToken") String maijiToken) throws Exception {
		logger.info("CapitalController.weixinPay,param is {},maijiToken is {}", JSON.toJSONString(param), maijiToken);
		return capitalMainLogService.weixinPay(param, maijiToken);
	}

	/**
	 * 微信小程序预支付
	 * 
	 * @return
	 * @throws Exception
	 */
	@PostMapping("weixiAppletPay")
	public BaseDataResDto<Map<String, Object>> weixiAppletPay(@RequestBody WeixinPayReqDto param, @RequestHeader("maijiToken") String maijiToken) throws Exception {
		logger.info("CapitalController.weixiAppletPay,param is {},maijiToken is {}", JSON.toJSONString(param),
				maijiToken);
		return capitalMainLogService.weixiAppletPay(param, maijiToken);
	}

    /**
     * 微信支付成功回调
     *
     * @param param
     * @return
     * @throws Exception
     */
    @PostMapping("weixinPayCallBack")
    public String weixinPayCallBack(@RequestBody PayResDto param) throws Exception {
        logger.info("CapitalController.weixinPayCallBack,param is {}", JSON.toJSONString(param));
        Map map = capitalMainLogService.weixinPayCallBack(param);
        String data = WXPayUtil.mapToXml(map);
        return data;
    }

	/**
	 * 支付宝支付
	 * 
	 * @param param
	 * @param maijiToken
	 * @return
	 * @throws Exception
	 */
	@PostMapping("alipay")
	public BaseDataResDto<AliPayResData> alipay(@RequestBody WeixinPayReqDto param, @RequestHeader("maijiToken") String maijiToken) throws Exception {
		logger.info("CapitalController.alipay,param is {},maijiToken is {}", JSON.toJSONString(param), maijiToken);

		return capitalMainLogService.alipay(param, maijiToken);
	}

	/**
	 * 支付宝支付成功回调
	 * 
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@PostMapping("alipayCallBack")
	public BaseDataResDto<Map<String, Object>> alipayCallBack(@RequestBody Map<String, String> param) throws Exception {

		logger.info("CapitalController.alipayCallBack,param is {}", JSON.toJSONString(param));

		Map<String, Object> map = capitalMainLogService.alipayCallBack(param);

		BaseDataResDto<Map<String, Object>> resParam = new BaseDataResDto<Map<String, Object>>(Status.SUCCESS);
		resParam.setData(map);

		return resParam;

	}

	/**
	 * 百度小程序支付成功回调
	 *
	 * @param param
	 * @return
	 * @throws Exception
	 */
	@PostMapping("bdXCXCallBack")
	public BdXCXResDto<Map<String, Object>> bdXCXCallBack(@RequestParam Map<String, String> param) {
		return capitalMainLogService.bdXCXCallBack(param);
	}

	/**
	 * 余额支付
	 * @param param
	 * @return
	 */
	@PostMapping("balancePay")
	public BaseDataResDto<String> balancePay(@RequestBody BaseDataReqDto<BalancePayReqData> param,@RequestHeader("maijiToken") String maijiToken) {
		logger.info("CapitalController.balancePay,param is {}", JSON.toJSONString(param));

		return capitalMainLogService.balancePay(param,maijiToken);
	}

	/**
	 * 余额消费明细
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("balanceConsumeFlow")
	public BaseDataResDto<List<FinancialDetailsResData>> balanceConsumeFlow(@RequestBody ReqMetaData param, @RequestHeader("maijiToken") String maijiToken){
		logger.info("CapitalController.balanceConsumeFlow,param is {},maijiToken is {}", JSON.toJSONString(param),maijiToken   );
   		return capitalMainLogService.balanceConsumeFlow(param,maijiToken);
	}

	/**
	 * 用户申请退款
	 * @return
	 */
	@PostMapping("userApplayRefund")
	public BaseResDto userApplayRefund(@RequestBody UserApplayRefundReqDto param, @RequestHeader(name = "maijiToken") String maijiToken) {
		logger.info("CapitalController.userApplayRefund,maijiToken is {},param is {}", maijiToken, JSON.toJSONString(param));
		return capitalMainLogService.userApplayRefund(param, maijiToken);
	}

	/**
	 * 用户撤销退款
	 * @return
	 */
	@PostMapping("userCancelRefund")
	public BaseResDto userCancelRefund(@RequestBody BaseDataReqDto<String> baseDataReqDto) {
        String orderId = baseDataReqDto.getData();
        if (StringUtil.isBlank(orderId)) return new BaseResDto(Status.PARAMETERERROR);
        return capitalMainLogService.userCancelRefund(orderId);
	}

	/**
	 * 退款成功回调接口
	 * 
	 * @throws Exception
	 */
	@PostMapping("refundCallBack")
	public String refundCallBack(@RequestBody WXRefundReqDto param) throws Exception {
		logger.info("CapitalController.refundCallBack,param is {}", JSON.toJSONString(param));
		Map map = capitalMainLogService.refundCallBack(param);
		return WXPayUtil.mapToXml(map);
	}

	/**
	 * 客服执行退款
	 * 
	 * @param baseDataReqDto
	 * @return
	 */
	@PostMapping("executeRefund")
	public BaseResDto executeRefund(@RequestBody BaseDataReqDto<String> baseDataReqDto) {
		String orderRefundId = baseDataReqDto.getData();
		if (StringUtil.isBlank(orderRefundId)) return new BaseResDto(Status.PARAMETERERROR);
		return capitalMainLogService.executeRefund(orderRefundId);
	}

	/**
	 * 客服审核退款申请
	 * @return
	 */
	@PostMapping("agreeApplyRefund")
	public BaseResDto agreeApplyRefund(@RequestBody BaseDataReqDto<OrderRefundReqData> baseDataReqDto) {
		OrderRefundReqData data = baseDataReqDto.getData();
		if (StringUtil.isBlank(data.getUuId()) || data.getRefundManey() == null)
			return new BaseResDto(Status.PARAMETERERROR);
		return capitalMainLogService.agreeApplyRefund(data);
	}

	/**
	 * 退货退款确认收货
	 * 
	 * @return
	 */
	@PostMapping("confirmReceived")
	public BaseResDto confirmReceived(@RequestBody BaseDataReqDto<OrderRefundReqData> baseDataReqDto) {
		String orderRefundId = baseDataReqDto.getData().getUuId();
		String orderId = baseDataReqDto.getData().getOrderId();
		if (StringUtil.isBlank(orderRefundId) || StringUtil.isBlank(orderId))
			return new BaseResDto(Status.PARAMETERERROR);
		return capitalMainLogService.confirmReceived(orderRefundId, orderId);
	}

	/**
	 * 获取用户退款申请列表
	 * 
	 * @return
	 */
	@PostMapping("findAllOrderRefunds")
	public BaseMetaResDto<List<ShoppingOrderRefundResData>> findAllOrderRefunds(@RequestBody BaseDataReqDto<OrderRefundReqData> baseDataReqDto) {
		OrderRefundReqData data = baseDataReqDto.getData();
		ReqMetaData metaData = baseDataReqDto.getMetaData();
		return capitalMainLogService.findAllOrderRefunds(data, metaData);
	}

	/**
	 * 统计退款类型数量
	 * 
	 * @return
	 */
	@GetMapping("findAllOrderRefundsTypeCount")
	public BaseDataResDto<List<Map<Integer, Integer>>> findAllOrderRefundsTypeCount() {
		return capitalMainLogService.findAllOrderRefundsTypeCount();
	}

	/**
	 * 提现
	 * @param baseDataReqDto
	 * @param maijiToken
	 */
	@PostMapping("withdraw")
	public BaseResDto withdraw(@RequestBody BaseDataReqDto<WithdrawReqData> baseDataReqDto,@RequestHeader("maijiToken") String maijiToken) {
        WithdrawReqData data = baseDataReqDto.getData();
        if(data.getAccountType() == null || data.getMoney() == null || data.getType() == null)
			return new BaseResDto(Status.PARAMETERERROR,"参数为空");
		if (data.getAccountType() == 1) return capitalMainLogService.withdrawDistribution(data, maijiToken);
		if (data.getAccountType() == 2) return capitalMainLogService.withdrawOrderReturn(data, maijiToken);
		return new BaseResDto(Status.ERROR.setMessage("提现账户类型错误"));
	}

    /**
     * 获取分销资金提现申请列表
     * @param baseDataReqDto
     */
    @PostMapping("findAllWithdrawApplys")
	public BaseMetaResDto<List<WithdrawApply>> findAllWithdrawApplys (@RequestBody BaseDataReqDto<WithdrawApply> baseDataReqDto) {
        WithdrawApply data = baseDataReqDto.getData();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        return withdrawApplyService.findAllWithdrawApplys(data, metaData);
    }

    /**
     * 审核分销资金提现申请
     * @param baseDataReqDto
     */
    @PostMapping("examineWithdrawApply")
	public BaseResDto examineWithdrawApply (@RequestBody BaseDataReqDto<WithdrawApply> baseDataReqDto) {
        WithdrawApply data = baseDataReqDto.getData();
        if (data.getExamine() == null) return new BaseResDto(Status.PARAMETERERROR);
        return withdrawApplyService.examineWithdrawApply(data);
    }

	/**
	 * 获取任务列表
	 * @param maijiToken
	 * @return
	 * @throws Exception 
	 */
	@PostMapping("getTaskList")
	public BaseDataResDto<List<TaskListResData>> getTaskList(@RequestHeader("maijiToken") String maijiToken) throws Exception{
		logger.info("CapitalController.getTaskList,maijiToken",maijiToken);
		
		return capitalMainLogService.getTaskList(maijiToken);
		
	}

	/**
	 * 查看是否绑定支付宝/微信 1：支付宝，2：微信
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("isBindWinthdrawAccount")
	public BaseDataResDto<List<BindWinthdrawAccountResData>> isBindWinthdrawAccount(@RequestBody BaseDataReqDto<List<Integer>> param,
                                                                                    @RequestHeader("maijiToken") String maijiToken){
		logger.info("CapitalController.isBindWinthdrawAccount,param is {},maijiToken", JSON.toJSONString(param),maijiToken);
		
		List<Integer> type = param.getData();
		if(type == null || type.size() == 0)
			return new BaseDataResDto<List<BindWinthdrawAccountResData>>(Status.PARAMETERERROR);
		
		return capitalMainLogService.isBindWinthdrawAccount(type,maijiToken);
	}
	/**
	 * 绑定提现账号
	 * @param param
	 * @param maijiToken
	 * @return
	 */
	@PostMapping("userBindWinthdrawAccount")
	public BaseResDto userBindWinthdrawAccount(@RequestBody BaseDataReqDto<UserBindWinthdrawAccountResData> param,
                                               @RequestHeader("maijiToken") String maijiToken) {
		logger.info("CapitalController.userBindWinthdrawAccount,param is {},maijiToken", JSON.toJSONString(param),maijiToken);
		
		return capitalMainService.userBindWinthdrawAccount( param,maijiToken);
	}

    /**
     * 获取用户资金流水列表
     * @param baseDataReqDto
     * @return
     */
    @PostMapping("findAllCapitalMainLogs")
    public BaseMetaResDto<List<CapitalMainLog>> findAllCapitalMainLogs(@RequestBody BaseDataReqDto<CapitalMainLog> baseDataReqDto) {
        String userId = baseDataReqDto.getData().getUserId();
        Integer capitalType = baseDataReqDto.getData().getCapitalType();
        List<Date> changeDates = baseDataReqDto.getData().getChangeDates();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        return capitalMainLogService.findAllCapitalMainLogs(userId, capitalType, changeDates, metaData);
    }

    /**
     * 获得用户提现记录列表
     * @return
     */
    @PostMapping("findAllWithdrawalRecords")
    public BaseMetaResDto<List<CapitalIOEntity>> findAllWithdrawalRecords(@RequestBody BaseDataReqDto<CapitalIOListReqData> baseDataReqDto) {
        String start = baseDataReqDto.getData().getType();
        String userId = baseDataReqDto.getData().getUserId();
        String nickName = baseDataReqDto.getData().getNickName();
        List<Date> inTimes = baseDataReqDto.getData().getInTimes();
        ReqMetaData metaData = baseDataReqDto.getMetaData();
        return capitalIOService.findAllWithdrawalRecords(start, inTimes, userId, nickName, metaData);
    }

}
